package gis.uzd_1;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;

import org.geotools.data.FeatureSource;
import org.geotools.feature.FeatureCollection;
import org.geotools.filter.text.cql2.CQL;
import org.geotools.swing.table.FeatureCollectionTableModel;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.filter.Filter;

/**
 * Detail table panel.
 * 
 * @version 0.1
 * @date 2010-04-23
 * @author Edmundas Matusevicius
 */
public class DetailPanel extends JPanel {
    public DetailPanel() {
        setLayout(new BorderLayout());
        
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        
        JScrollPane scrollPane = new JScrollPane(table);
        
        add(text, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);
        
        setUpActions();
    }
    
    private void setUpActions() {
        text.addActionListener(new ActionListener() {
            @SuppressWarnings("unchecked")
            public void actionPerformed(ActionEvent event) {
                try {
                    Filter filter = CQL.toFilter(text.getText());
                    FeatureCollection<SimpleFeatureType, SimpleFeature> features = source.getFeatures(filter);
                    FeatureCollectionTableModel model = new FeatureCollectionTableModel(features);
                    
                    table.setModel(model);
                } catch (Exception e) {
//                    e.printStackTrace();
                }
                
                text.setText(null);
            }
        });
        
        table.addMouseListener(new MouseAdapter() {
            public void mouseReleased(MouseEvent event) {
                Object[] IDs = new Object[table.getSelectedRowCount()];
                
                for (int i = 0; i < IDs.length; i++)
                    IDs[i] = table.getValueAt(table.getSelectedRows()[i], 0);
                
                DataPanel.mapPanel.selectFeatures(IDs);
            }
        });
    }
    
    // table data
    
    static JTable table = new JTable();
    @SuppressWarnings("unchecked")
    static FeatureSource source;
    
    // search/filter field
    
    static JTextField text = new JTextField();
}
